import numpy as np
import cv2 as cv


def create_callback(state_key):
    """创建回调函数的工厂函数"""

    def callback(value):
        state[state_key] = value

    return callback


# 初始化状态
state = {
    'R': 100,  # 红色初始值
    'G': 0,  # 绿色初始值
    'B': 0,  # 蓝色初始值
    'switch': 0  # 开关状态
}


# 创建窗口和控件
def create_interface():
    """创建GUI界面"""
    # 创建黑色背景图像
    img = np.zeros((300, 512, 3), dtype=np.uint8)
    cv.namedWindow('Color Picker')

    # 创建RGB滑动条
    cv.createTrackbar('R (0-255)', 'Color Picker', state['R'], 255, create_callback('R'))
    cv.createTrackbar('G (0-255)', 'Color Picker', state['G'], 255, create_callback('G'))
    cv.createTrackbar('B (0-255)', 'Color Picker', state['B'], 255, create_callback('B'))

    # 创建开关
    cv.createTrackbar('OFF/ON', 'Color Picker', 0, 1, create_callback('switch'))

    return img


def main():
    """主程序逻辑"""
    img = create_interface()

    while True:
        # 显示当前图像
        cv.imshow('Color Picker', img)

        # 检查按键输入（ESC退出）
        if cv.waitKey(1) == 27:
            break

        # 根据开关状态更新图像
        if state['switch']:
            # OpenCV使用BGR顺序
            img[:] = [state['B'], state['G'], state['R']]
        else:
            img[:] = 0  # 关闭时显示黑色

    # 清理资源
    cv.destroyAllWindows()


if __name__ == '__main__':
    main()